import { HttpError, WEBSOCKETS, toSuccess, useEntityManager } from "@sker/core";
import { useData } from "@sker/runtime";
import { AutoDevice } from "@sker/entities";
import { InjectionToken, container } from "tsyringe";
import { z } from "zod";

export default async () => {
    const input = z.object({
        id: z.string(),
        code: z.string(),
        uuid: z.string()
    })
    const body = input.parse(useData());
    const result = await useEntityManager(async m => {
        const device = await m.findOne(AutoDevice, { where: { device_uuid: body.uuid } })
        if (!device) throw new HttpError(`无效token`)
        const websockets = container.resolve(WEBSOCKETS)
        const wss = websockets.get(device.device_uuid)
        if (!wss) throw new HttpError(`设备不在线`)
        return new Promise<boolean>((resolve, reject) => {
            wss.send(JSON.stringify({
                type: CLOUD_CODE,
                payload: {
                    id: body.id,
                    code: body?.code,
                    type: 'script'
                }
            }), err => {
                if (err) {
                    return resolve(false)
                }
                return resolve(true)
            })
        })

    })
    return toSuccess(result)
}
interface ICloudCode {
    id: string;
    code: string;
    timeout?: number;
}
const CLOUD_CODE: InjectionToken<ICloudCode> = `CLOUD_CODE`
